package com.company.statistician;

import com.company.TrianglePacket;
import com.company.exception.NoMatchException;
import com.company.graphgetter.GraphGetter;
import com.company.graphgetter.NodeGetterWithGraph;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class NodeDistributedColumnStatistician implements Statistician {
    int barrelSize;
    int maxBarrelIndex;
    int lumbda;
    List<TrianglePacket> packets;
    HashMap<Integer, Integer> barrels;

    public NodeDistributedColumnStatistician(NodeGetterWithGraph getterWithGraph, int barrelSize) {
        this.barrelSize = barrelSize;
        this.barrels = new HashMap<>();
    }

    @Override
    public void equipData(GraphGetter graphGetter) throws NoMatchException {
        if (!(graphGetter instanceof NodeGetterWithGraph)) {
            throw new NoMatchException("Getter is not the type of NodeGetterWithGraph");
        }
        NodeGetterWithGraph getter = (NodeGetterWithGraph) graphGetter;
        packets = CopyList(getter.ranks());
    }

    @Override
    public void calcData() {
        for (TrianglePacket packet : packets) {
            addIntoBarrel(packet.getValue());
        }
    }

    private void addIntoBarrel(int value) {
        int barrelIndex = value / barrelSize;
        if (barrelIndex > maxBarrelIndex) {
            maxBarrelIndex = barrelIndex;
        }
        if (maxBarrelIndex == 30940) {
            System.out.println("DEBUG");
        }
        barrels.put(barrelIndex, barrels.getOrDefault(barrelIndex, 0) + 1);
    }

    @Override
    public Object outputData() {
        ArrayList<Column> columns = new ArrayList<>();
        for (int barrelIndex = 0; barrelIndex < maxBarrelIndex; barrelIndex++) {
            Integer barrelCount = barrels.getOrDefault(barrelIndex, 0);
            Column column = new Column(barrelIndex * barrelSize, barrelSize, barrelCount);
            columns.add(column);
        }
        return columns;
    }

    private List<TrianglePacket> CopyList( List<TrianglePacket> list) {
        ArrayList<TrianglePacket> trianglePackets = new ArrayList<>();
        trianglePackets.addAll(list);
        return trianglePackets;
    }
}
